package com.kgc.onlineLife.controller;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.kgc.onlineLife.bean.Customer;
import com.kgc.onlineLife.bean.User;
import com.kgc.onlineLife.service.CustomerService;
import com.kgc.onlineLife.service.UserService;
import com.kgc.onlineLife.util.EncodeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
* @author: HarryXzy
* @date: 2022/4/14 5:41 下午
* @return:
* @description: 前台后台 登陆注册 controller
**/
@Controller
public class LoginRegiController {


    //Kaptcha验证码
    @Autowired
    private DefaultKaptcha defaultKaptcha;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private UserService userService;


    /**
    * @author: HarryXzy
    * @date: 2022/4/14 5:49 下午
    * @return:
    * @description: 去注册页面
    **/
    @RequestMapping("/fore/foreRegisterUI")
    public String registerUI(){
        return "/Fore/forepage/foreRegister";
    }

    /**
    * @author: HarryXzy
    * @date: 2022/4/14 5:50 下午
    * @return:
    * @description: 去登陆页面
    **/
    @RequestMapping("/fore/foreLoginUI")
    public String foreLoginUI(){
        return "/Fore/forepage/forelogin";
    }


    /**
    * @author: HarryXzy
    * @date: 2022/4/14 5:25 下午
    * @return: 
    * @description: 前台用户注册
    **/
    @RequestMapping("/fore/foreRegister")
    public String register(@Valid Customer customer,
                           BindingResult result,
                           Model model,
                           HttpSession session,
                           @RequestParam("code")String code){
        //获取正确的code
        String rightCode = (String) session.getAttribute("rightCode");
        //验证码正确
        if (StringUtils.isNotBlank(code) &&rightCode.equals(code))
        {
            //jsr303校验
            if(result.hasErrors()){
                model.addAttribute("jsrError","true");
                return "/Fore/forepage/foreRegister";
            }else {
                customer.setStatus(1);
                //MD5加密
                String s = EncodeUtils.testDigest(customer.getPassword());
                customer.setPassword(s);

                customerService.save(customer);
                session.removeAttribute("rightCode");
                return "/Fore/forepage/registerSuccess";
            }
        }else{
            //验证码错误前端标识显示
            model.addAttribute("msg","验证码错误");
            return "/Fore/forepage/foreRegister";
        }

    }

    /**
    * @author: HarryXzy
    * @date: 2022/4/14 9:13 下午
    * @return:
    * @description: ajax校验用户名是否重复
    **/
    @ResponseBody
    @RequestMapping("/fore/nameCheck")
    public String nameCheck(String name){
        Customer c=customerService.checkName(name);
        System.out.println(c);
        if(c!=null){
            return "ERROR";
        }
        return "SUCCESS";
    }

    /**
    * @author: HarryXzy
    * @date: 2022/4/14 4:42 下午
    * @return:
    * @description: 前台用户登陆
    **/
    @RequestMapping("/fore/foreLogin")
    public String foreLogin(Customer customer,
                            HttpSession session,
                            Model model,
                            @RequestParam("code")String code){

        //获取正确的code
        String rightCode = (String) session.getAttribute("rightCode");
        //验证码正确
        if (StringUtils.isNotBlank(code) &&rightCode.equals(code))
        {
            //验证登陆操作
            //MD5加密
            String s = EncodeUtils.testDigest(customer.getPassword());
            customer.setPassword(s);

            Customer cst = customerService.foreLogin(customer);
            if (cst!=null && cst.getStatus() != 0){
                //登陆成功
                session.setAttribute("cst",cst);
                session.removeAttribute("rightCode");
                return "redirect:/fore/foreIndex";
            }else {
                //登陆失败
                model.addAttribute("msg","true");
                return "/Fore/forepage/forelogin";
            }
        }else{
            //验证码错误前端标识显示
            model.addAttribute("msg","codeError");
            return "/Fore/forepage/forelogin";
        }
    }


    /**
    * @author: HarryXzy
    * @date: 2022/4/20 7:27 下午
    * @return:
    * @description: 前台用户模态框登陆
    **/
    @ResponseBody
    @RequestMapping("/fore/foreMtLogin")
    public String foreModelLogin(@RequestParam("name")String name,
                                 @RequestParam("password")String pwd,
                                 @RequestParam("code")String code,
                                 HttpSession session){
        //获取正确的code
        String rightCode = (String) session.getAttribute("rightCode");
        //验证码正确
        if (StringUtils.isNotBlank(code) &&rightCode.equals(code))
        {
            Customer customer = new Customer();
            customer.setName(name);
            //MD5加密
            String s = EncodeUtils.testDigest(pwd);
            customer.setPassword(s);
            //验证登陆操作
            Customer cst = customerService.foreLogin(customer);
            if (cst!=null){
                //登陆成功
                session.setAttribute("cst",cst);
                session.removeAttribute("rightCode");
                return "true";
            }else {
                //登陆失败
                return "customerError";
            }
        }else{
            //验证码错误
            return "codeError";
        }
    }

    /**
    * @author: HarryXzy
    * @date: 2022/4/14 4:52 下午
    * @return:
    * @description: kaptcha验证码
    **/
    @RequestMapping("/defaultKaptcha")
    public void defaultKaptcha(HttpSession session, HttpServletResponse response)
            throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            // 生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            session.setAttribute("rightCode", createText);
            // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }


    /**
    * @author: HarryXzy
    * @date: 2022/4/14 9:11 下午
    * @return:
    * @description: 前台退出登陆
    **/
    @RequestMapping("/fore/foreCstLoginOut")
    public String cstLoginOut(HttpSession session){
        session.setAttribute("cst",null);
        return "redirect:/fore/foreLoginUI";
    }


    /**
    * @author: HarryXzy
    * @date: 2022/4/15 5:34 下午
    * @return:
    * @description: 后台管理员登陆
    **/
    @RequestMapping("/admin/login")
    public String adminLogin(User user,
                             HttpSession session,
                             Model model,
                             @RequestParam("code")String code){
        System.out.println(user);
        //获取正确的code
        String rightCode = (String) session.getAttribute("rightCode");
        //验证码正确
        if (StringUtils.isNotBlank(code) &&rightCode.equals(code))
        {
            //MD5加密
            String s = EncodeUtils.testDigest(user.getPassword());
            user.setPassword(s);
            //验证登陆操作
            User u = userService.adminLogin(user);
            if (u!=null){
                //登陆成功
                session.setAttribute("loginAdmin",u);
                session.removeAttribute("rightCode");
                return "forward:/admin/dashboard";
            }else {
                //登陆失败
                model.addAttribute("msg","用户名或密码错误");
                return "/Admin/login";
            }
        }else{
            //验证码错误前端标识显示
            model.addAttribute("msg","验证码错误");
            return "/Admin/login";
        }

    }


    /**
    * @author: HarryXzy
    * @date: 2022/4/15 7:02 下午
    * @return:
    * @description: 后台退出登陆
    **/
    @RequestMapping("/admin/logout")
    public String adminLoginOut(HttpSession session){
        session.removeAttribute("loginAdmin");
        return "redirect:/Admin/login.jsp";
    }
}
